from django.views.decorators.csrf import csrf_exempt
from base.myjson import JSONResponse
from app.model.NewsModel import QyNews,News_getRespondent,News_getApplicant
from base.my_page import mypage
import json,time

# Create your views here.



@csrf_exempt
def friendApplication(request):
    '''
    查询'球友'发送来的申请
    :param request:
    :return:
    '''
    if request.method == 'GET':
        page = request.GET.get('page')
        id = request.GET.get('respondent')
        objs = QyNews.objects.filter(respondent_id=int(id))

        p = mypage(page,objs)
        obj = p['page_list']
        total = p['page_sum']

        serializer = News_getApplicant(obj,many=True)
        return JSONResponse(0,serializer.data,total)
    else:
        return JSONResponse(1054)



@csrf_exempt
def myApplication(request):
    '''
    查询'本人'发出的申请信息
    :param request:
    :return:
    '''
    if request.method == 'GET':
        page = request.GET.get('page')
        id = request.GET.get('applicant')
        objs = QyNews.objects.filter(applicant_id=int(id))

        p = mypage(page,objs)
        obj = p['page_list']
        total = p['page_sum']

        serializer = News_getRespondent(obj,many=True)
        return JSONResponse(0,serializer.data,total)
    else:
        return JSONResponse(1054)



@csrf_exempt
def news_create(request):
    '''
    创建申请信息
    :param request:
    :return:
    '''
    if request.method == 'POST':
        data = json.loads(request.body)

        # 申请人 与 被申请人 不能一致
        if data['applicant_id']== data['respondent_id']:
            return JSONResponse(1005)

        # 创建申请信息
        try:
            obj = QyNews(
                applicant_id = data.get('applicant_id'),
                respondent_id = data.get('respondent_id'),
                content = data.get('content'),
                apply_time = str(time.time()),
            )
            obj.save()
        except:
            return JSONResponse(1007)

        objs = QyNews.objects.get(pk=obj.pk)
        serializer = News_getRespondent(objs, many=False)
        return JSONResponse(0,serializer.data)

    else:
        return JSONResponse(1055)
